import 'package:cached_network_image/cached_network_image.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/modules/recipe/data/model/recipe_placeholder_data.dart';
import 'package:casdon/modules/recipe/ui/widgets/play_orverlay_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class NineGridWidget extends StatelessWidget {
  final String title;
  final String content;
  final List<String> images;
  final List<String> videoUrls;
  final double spacing;
  final double imageSize;
  final double singleImageHeight;
  final String? placeholder;
  final TextStyle? titleStyle;
  final TextStyle? contentStyle;
  final void Function(int index, String imageUrl)? onImageTap;
  final void Function(int index, String videoUrl)? onVideoTap;
  final VoidCallback? onContentTap;

  const NineGridWidget({
    super.key,
    required this.title,
    required this.content,
    required this.images,
    this.videoUrls = const [],
    this.spacing = 6.0,
    this.imageSize = 113.0,
    this.singleImageHeight = 206.0,
    this.placeholder,
    this.titleStyle,
    this.contentStyle,
    this.onImageTap,
    this.onVideoTap,
    this.onContentTap,
  });

  bool _isNetwork(String path) =>
      path.startsWith('http://') || path.startsWith('https://');

  bool _isVideo(String? url) =>
      url != null && (url.startsWith('http://') || url.startsWith('https://'));

  /// ✅ 构建单个图片格子（含视频覆盖层）
  Widget _buildMediaCell({
    required int index,
    required String imageUrl,
    required double width,
    required double height,
  }) {
    final videoUrl = (index < videoUrls.length) ? videoUrls[index] : ''; // 安全取值
    final hasVideo = _isVideo(videoUrl);

    final isNet = _isNetwork(imageUrl);
    final placeholderPath = placeholder ?? recipePlaceHolderImgUrl;
    final hasPlaceholder = true;
    final isPlaceholderNet = hasPlaceholder && _isNetwork(placeholderPath);

    Widget placeholderWidget = isPlaceholderNet
        ? CachedNetworkImage(
            imageUrl: placeholderPath,
            width: width,
            height: height,
            fit: BoxFit.cover,
            memCacheWidth: width.isFinite ? (width * 2).toInt() : null,
            memCacheHeight: height.isFinite ? (height * 2).toInt() : null,
            fadeInDuration: Duration.zero,
          )
        : Image.asset(
            placeholderPath,
            width: width,
            height: height,
            fit: BoxFit.cover,
          );

    Widget imageChild;
    if (width.isFinite && height.isFinite) {
      imageChild = SizedBox(
        width: width,
        height: height,
        child: FittedBox(
          fit: BoxFit.cover,
          alignment: Alignment.center,
          clipBehavior: Clip.hardEdge,
          child: isNet
              ? CachedNetworkImage(
                  key: ValueKey('nine_grid_img9_$imageUrl'),
                  imageUrl: imageUrl,
                  fit: BoxFit.cover,
                  cacheKey: imageUrl,
                  memCacheWidth: (width * 2).toInt(),
                  memCacheHeight: (height * 2).toInt(),
                  maxWidthDiskCache: (width * 2).toInt(),
                  maxHeightDiskCache: (height * 2).toInt(),
                  fadeInDuration: Duration.zero,
                  placeholder: (context, url) => placeholderWidget,
                  errorWidget: (context, url, error) => placeholderWidget,
                )
              : Image.asset(
                  imageUrl,
                  fit: BoxFit.cover,
                  errorBuilder: (_, __, ___) => placeholderWidget,
                ),
        ),
      );
    } else {
      // 对于无限约束，避免 FittedBox 断言，直接用普通铺满
      imageChild = SizedBox(
        width: width.isFinite ? width : double.infinity,
        height: height.isFinite ? height : null,
        child: isNet
            ? CachedNetworkImage(
                key: ValueKey('nine_grid_img9_$imageUrl'),
                imageUrl: imageUrl,
                fit: BoxFit.cover,
                cacheKey: imageUrl,
                fadeInDuration: Duration.zero,
                placeholder: (context, url) => placeholderWidget,
                errorWidget: (context, url, error) => placeholderWidget,
              )
            : Image.asset(
                imageUrl,
                fit: BoxFit.cover,
                errorBuilder: (_, __, ___) => placeholderWidget,
              ),
      );
    }

    final imageWidget = ClipRRect(
      borderRadius: BorderRadius.circular(12.r),
      child: Stack(
        alignment: Alignment.center,
        children: [
          // 图片内容
          imageChild,

          // ✅ 如果是视频，叠加一个播放按钮
          if (hasVideo)
            PlayOverlayButton(
              onTap: () {
                onVideoTap?.call(index, videoUrl);
              },
            ),
        ],
      ),
    );

    return GestureDetector(
      onTap: () {
        if (hasVideo) {
          onVideoTap?.call(index, videoUrl);
        } else {
          onImageTap?.call(index, imageUrl);
        }
      },
      child: imageWidget,
    );
  }

  /// 按规则返回占位位置（1..9）
  List<int> _getImagePositions(int count) {
    switch (count) {
      case 1:
        return [1];
      case 2:
        return [1, 2];
      case 3:
        return [1, 2, 3];
      case 4:
        return [1, 2, 4, 5];
      case 5:
        return [1, 2, 3, 4, 5];
      case 6:
        return [1, 2, 3, 4, 5, 6];
      case 7:
        return [1, 2, 3, 4, 5, 6, 7];
      case 8:
        return [1, 2, 3, 4, 5, 6, 7, 8];
      default:
        return [1, 2, 3, 4, 5, 6, 7, 8, 9];
    }
  }

  @override
  Widget build(BuildContext context) {
    final defaultTitleStyle = context.textTheme.bodyLarge!.copyWith(
      color: context.customColorThemeNonNull.textColor1,
    );

    final defaultContentStyle = context.textTheme.bodyMedium!.copyWith(
      color: context.customColorThemeNonNull.textColor1,
    );

    final imageCount = images.length;

    // 无图
    if (imageCount == 0) {
      final textSection = _buildTextSection(
        defaultTitleStyle,
        defaultContentStyle,
      );
      return textSection ?? const SizedBox.shrink();
    }

    // 单图
    if (imageCount == 1) {
      final textSection = _buildTextSection(
        defaultTitleStyle,
        defaultContentStyle,
      );
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (textSection != null) textSection,
          SizedBox(height: 12.h),
          _buildMediaCell(
            index: 0,
            imageUrl: images.first,
            width: double.infinity,
            height: singleImageHeight.h,
          ),
        ],
      );
    }

    // 多图布局
    final positions = _getImagePositions(imageCount);
    final maxPos = positions.isNotEmpty ? positions.last : 0;
    final rows = ((maxPos - 1) ~/ 3) + 1;

    final textSection = _buildTextSection(
      defaultTitleStyle,
      defaultContentStyle,
    );

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (textSection != null) textSection,
        SizedBox(height: 12.h),
        Column(
          children: List.generate(rows, (rowIndex) {
            final isLastRow = rowIndex == rows - 1;
            final List<Widget> rowChildren = [];

            for (int col = 0; col < 3; col++) {
              final gridIndex = rowIndex * 3 + col + 1;
              final posIndex = positions.indexOf(gridIndex);

              Widget cell;
              if (posIndex != -1 && posIndex < images.length) {
                cell = _buildMediaCell(
                  index: posIndex,
                  imageUrl: images[posIndex],
                  width: imageSize.w,
                  height: imageSize.w,
                );
              } else {
                cell = SizedBox(width: imageSize.w, height: imageSize.w);
              }

              rowChildren.add(cell);

              if (col != 2) {
                rowChildren.add(SizedBox(width: spacing.w));
              }
            }

            return Padding(
              padding: EdgeInsets.only(bottom: isLastRow ? 0 : spacing.w),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: rowChildren,
              ),
            );
          }),
        ),
      ],
    );
  }

  Widget? _buildTextSection(
    TextStyle defaultTitleStyle,
    TextStyle defaultContentStyle,
  ) {
    if (title.isEmpty && content.isEmpty) {
      return null;
    }

    final List<Widget> children = [];

    if (title.isNotEmpty) {
      children.add(
        Text(
          title,
          style: titleStyle ?? defaultTitleStyle,
          maxLines: 3,
          overflow: TextOverflow.ellipsis,
        ),
      );
    }

    if (content.isNotEmpty) {
      children.add(SizedBox(height: 6.h));
      children.add(
        Text(
          content,
          style: contentStyle ?? defaultContentStyle,
          maxLines: 5,
          overflow: TextOverflow.ellipsis,
        ),
      );
    }

    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onContentTap ?? () {},
      child: SizedBox(
        width: double.infinity,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: children,
        ),
      ),
    );
  }
}
